
// 产品模块
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const {User} = require('./users');


const Video = sequelize.define('videos', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    name: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    des: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    url: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    commentNumber: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
    }

});
const Comment = sequelize.define('comments', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    comment: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    videoId: {
        type: DataTypes.UUID,
        allowNull: false,
    },
    userName: {
        type: DataTypes.TEXT,
        allowNull: false,
    }
});

async function initVideo() {
    await Video.sync();
    await Comment.sync();
    const videoJSON = [
        {
            name: '英语口语',
            des: '零基础英语口语学习视频',
            url: 'https://vd4.bdstatic.com/mda-jirwkhgyvmh6c21h/sc/mda-jirwkhgyvmh6c21h.mp4?v_from_s=nj_haokan_4469&auth_key=1617950235-0-0-f49742936948792abe078849b757aece&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '少儿英语启蒙',
            des: '儿童启蒙英语单词学习视频',
            url: 'https://vd2.bdstatic.com/mda-km4mdggj46qn06gs/sc/cae_h264_clips/1607152406/mda-km4mdggj46qn06gs.mp4?auth_key=1617953448-0-0-d440e86b70c89b5ec458ecb3025d695b&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '少儿英语学习视频',
            des: '少儿英语学习视频',
            url: 'https://vd2.bdstatic.com/mda-kkbzw7n43uhabnp5/hd/mda-kkbzw7n43uhabnp5.mp4?v_from_s=hba_haokan_4469&auth_key=1617954337-0-0-2f2236838647f32610b242942b43aac4&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '搞笑英语',
            des: '搞笑英语动画，趣味英语学习视频，一起来学习下吧小伙伴们',
            url: 'https://vd2.bdstatic.com/mda-jkhjb9xgdi60ud18/sc/mda-jkhjb9xgdi60ud18.mp4?v_from_s=tc_haokan_4469&auth_key=1617954919-0-0-6fd2c64399de33898ba14ac65ae4eff2&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '英语日常',
            des: '英语日常口语教学，一边看视频还能学习英语了，一起来学习下吧',
            url: 'https://vd2.bdstatic.com/mda-jiftdkr6ndtxf2sx/sc/mda-jiftdkr6ndtxf2sx.mp4?v_from_s=tc_haokan_4469&auth_key=1617954958-0-0-628ea5274b98813ef1436b2f80d9aeb6&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '英语学习视频教程',
            des: '英语学习视频教程 -培训',
            url: 'https://vd4.bdstatic.com/mda-kcm5c48dzzpbakht/sc/mda-kcm5c48dzzpbakht.mp4?v_from_s=hba_haokan_4469&auth_key=1617955217-0-0-e14db6e268a7bdd6ca515d52a39b44ee&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
        {
            name: '英语学习必看视频',
            des: '英语学习必看视频',
            url: 'https://vd4.bdstatic.com/mda-jise6kh6ha7q1645/sc/mda-jise6kh6ha7q1645.mp4?v_from_s=hba_haokan_4469&auth_key=1617955257-0-0-a537569591e6a4451696fbd16ee4022c&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=',
        },
    ];
    const count = await Video.count();
    if (0 === count) {
        await Video.bulkCreate(videoJSON);
        console.log('初始化视频成功！');
    }
}
initVideo();

const videoModel = {
    async getVideos(ctx) {
        const params = ctx.query;
        // const count = await Words.count();
        const {offset = 0, limit = 10, keywords} = params;

        let info = await Video.findAndCountAll(
            {
                where: {
                    name: {
                        [Op.like]: '%' + (keywords || '') + '%',
                    },
                },
                limit: parseInt(limit),
                offset: parseInt(offset),
            }
        );
        ctx.pageRes({
            limit,
            offset,
            list: info.rows,
            total: info.count,
        });
    },
    async comment(ctx) {
        const params = ctx.request.body;
        if (!params.comment) {
            ctx.errorParams('请输入评论内容！');
            return ;
        } else if (!params.videoId) {
            ctx.errorParams('没传视频id！');
            return ;
        }
        const video = await Video.findOne({
            where: {
                id: params.videoId,
            },
            raw: true,
        });
        if (!video) {
            ctx.errorParams('视频id有问题哟！');
            return ;
        }
        console.log(ctx.session.sessionData);
        const comment = await Comment.create({
            ...params,
            userName: ctx.session.sessionData.nickName,
        });
        video.commentNumber += 1;

        await Video.update({
            ...video,
        }, {
            where: {
                id: video.id
            },
        });

        ctx.success('评论成功！', comment);
    },
    async getComment(ctx) {
        const params = ctx.query;
        // const count = await Words.count();
        const {id} = params;
        if (!id) {
            ctx.errorParams('请传视频id！');
            return ;
        }
        const info = await Comment.findAll({
            where: {
                videoId: id,
            },
            raw: true,
        });

        ctx.success('查询成功！', info);
    },
    async addHistory(ctx) {
        const params = ctx.request.body;
        // const count = await Words.count();
        const {id} = params;
        if (!id) {
            ctx.errorParams('请传视频id！');
            return ;
        }
        const info = await User.findOne({
            where: {
                id: ctx.session.sessionData.id,
            },
            raw: true,
        });
        const historyVideoIds = info.historyVideoIds ? info.historyVideoIds.split(',') : [];
        if (-1 === historyVideoIds.indexOf(id)) {
            historyVideoIds.push(id);
        }
        await User.update({
            ...info,
            historyVideoIds: historyVideoIds.join(),
        }, {
            where: {
                id: ctx.session.sessionData.id
            },
        });

        ctx.success('成功！');
    },
    async videoHistory(ctx) {
        const info = await User.findOne({
            where: {
                id: ctx.session.sessionData.id,
            },
            raw: true,
        });

        const historyVideoIds = info.historyVideoIds ? info.historyVideoIds.split(',') : [];
        if (0 === historyVideoIds.length) {
            ctx.success('成功！', historyVideoIds);
        } else {
            let videos = await Video.findAll(
                {
                    where: {
                        id: {
                            [Op.in]: historyVideoIds,
                        },
                    },
                }
            );
            ctx.success('查询成功！', videos);
        }
    }
};


module.exports = {
    videoModel,
    Video
};